/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.alternativesrating;

import controller.alternative.ranks.ControllerAlternativeRanks;
import data.ACStorage;
import exception.MarkNotInSatScaleException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Ivan
 */
public class FrmRankAlternativesByCriteria extends javax.swing.JDialog {
    
    private JPanel panelAC;
    int criteriaCounter = 0;

    /**
     * Creates new form JDialogAC
     */
    public FrmRankAlternativesByCriteria(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        cBox = (String) cmbNormalize.getSelectedItem();
        checkButtons();
    }
    public String cBox;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlOptions = new javax.swing.JPanel();
        btnNormalize = new javax.swing.JButton();
        cmbNormalize = new javax.swing.JComboBox();
        btnPrevious = new javax.swing.JButton();
        btnNext = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        btnAverageValues = new javax.swing.JButton();
        pnlTable = new javax.swing.JPanel();
        pnlSlider = new javax.swing.JPanel();
        slderMarkAlternatives = new javax.swing.JSlider();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        pnlOptions.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnNormalize.setText("Normalize");
        btnNormalize.setAlignmentX(5.0F);
        btnNormalize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNormalizeActionPerformed(evt);
            }
        });

        cmbNormalize.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "L1Normalization", "L2Normalization", "LInfinityNormalization", "BestWorstNormalization" }));
        cmbNormalize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbNormalizeActionPerformed(evt);
            }
        });

        btnPrevious.setText("<<");
        btnPrevious.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPreviousActionPerformed(evt);
            }
        });

        btnNext.setText(">>");
        btnNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNextActionPerformed(evt);
            }
        });

        jLabel1.setText("Choose type of normalization for alternative marks:");

        btnAverageValues.setText("Average Values");
        btnAverageValues.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAverageValuesActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnlOptionsLayout = new javax.swing.GroupLayout(pnlOptions);
        pnlOptions.setLayout(pnlOptionsLayout);
        pnlOptionsLayout.setHorizontalGroup(
            pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlOptionsLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pnlOptionsLayout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnPrevious, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlOptionsLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 19, Short.MAX_VALUE)
                        .addComponent(cmbNormalize, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnNormalize, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                    .addComponent(btnNext, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
                    .addComponent(btnAverageValues, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnlOptionsLayout.setVerticalGroup(
            pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlOptionsLayout.createSequentialGroup()
                .addGap(5, 5, 5)
                .addGroup(pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNormalize)
                    .addComponent(cmbNormalize, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
                .addComponent(btnAverageValues)
                .addGap(18, 18, 18)
                .addGroup(pnlOptionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnPrevious)
                    .addComponent(btnNext)))
        );

        getContentPane().add(pnlOptions, java.awt.BorderLayout.PAGE_END);

        pnlTable.setBorder(javax.swing.BorderFactory.createTitledBorder("Marks preview"));
        pnlTable.setLayout(new java.awt.BorderLayout());
        getContentPane().add(pnlTable, java.awt.BorderLayout.CENTER);

        pnlSlider.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pnlSlider.setName(""); // NOI18N

        slderMarkAlternatives.setMajorTickSpacing(1);
        slderMarkAlternatives.setMaximum(8);
        slderMarkAlternatives.setMinimum(-8);
        slderMarkAlternatives.setPaintTicks(true);
        slderMarkAlternatives.setSnapToTicks(true);
        slderMarkAlternatives.setValue(0);
        slderMarkAlternatives.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                slderMarkAlternativesMouseReleased(evt);
            }
        });
        slderMarkAlternatives.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                slderMarkAlternativesStateChanged(evt);
            }
        });
        slderMarkAlternatives.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                slderMarkAlternativesKeyReleased(evt);
            }
        });

        jLabel2.setText("  9       8        7       6       5        4       3        2       1        2        3       4        5        6       7       8       9");

        javax.swing.GroupLayout pnlSliderLayout = new javax.swing.GroupLayout(pnlSlider);
        pnlSlider.setLayout(pnlSliderLayout);
        pnlSliderLayout.setHorizontalGroup(
            pnlSliderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSliderLayout.createSequentialGroup()
                .addGap(50, 50, 50)
                .addGroup(pnlSliderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(slderMarkAlternatives, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE))
                .addContainerGap(58, Short.MAX_VALUE))
        );
        pnlSliderLayout.setVerticalGroup(
            pnlSliderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlSliderLayout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(slderMarkAlternatives, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        getContentPane().add(pnlSlider, java.awt.BorderLayout.PAGE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmbNormalizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbNormalizeActionPerformed
        JComboBox cb = (JComboBox) evt.getSource();
        cBox = (String) cb.getSelectedItem();
    }//GEN-LAST:event_cmbNormalizeActionPerformed
    
    private void btnNormalizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNormalizeActionPerformed
        System.out.println(cBox);
        try {
            ControllerAlternativeRanks.getInstance().normalize(cBox, ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter));
            TblModelNormalizedAlternatives tblModelNormalizedAlternatives = new TblModelNormalizedAlternatives(
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter));
            ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().setModel(tblModelNormalizedAlternatives);
            slderMarkAlternatives.setEnabled(false);
            btnNormalize.setEnabled(false);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }

        //todo postaviti model tabele za normalizovane vrednsoti

//        for (int i = 0; i < ACStorage.getInstance().getAlternatives().size(); i++) {
//            Map map = ACStorage.getInstance().getAlternatives().get(i).getMarks();
//            switch (cBox) {
//                case "L1 Normalization": {
//
//                    Map result = L1Normalization.L1Normalize((HashMap) map);
//                    ACStorage.getInstance().getAlternatives().get(i).setNormalizedMarks(result);
//                    break;
//                }
//                case "L2 Normalization": {
//                    Map result = L2Normalization.L2Normalize((HashMap) map);
//                    ACStorage.getInstance().getAlternatives().get(i).setNormalizedMarks(result);
//                    break;
//                }
//                case "Infinity Normalization": {
//                    Map result = LInfinityNormalization.LInfinityNormalize((HashMap) map);
//                    ACStorage.getInstance().getAlternatives().get(i).setNormalizedMarks(result);
//                    break;
//                }
//                case "Best-worst Normalization": {
//                    Map result = BestWorstNormalization.BestWorstNormalization((HashMap) map);
//                    ACStorage.getInstance().getAlternatives().get(i).setNormalizedMarks(result);
//                    break;
//                }
//            }

    }//GEN-LAST:event_btnNormalizeActionPerformed
    
    private void btnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNextActionPerformed
        ++criteriaCounter;
        if (ACStorage.getInstance().getGoal().getListCriteria().size() > criteriaCounter) {
            TblModelAlternatives tblModelAlternatives = new TblModelAlternatives(
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter));
            ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().setModel(tblModelAlternatives);
        }
        if(!slderMarkAlternatives.isEnabled()){
            slderMarkAlternatives.setEnabled(true);
        }
        checkButtons();
    }//GEN-LAST:event_btnNextActionPerformed
    
    private void slderMarkAlternativesStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_slderMarkAlternativesStateChanged
//        System.out.println(jSlider1.getValue());
//        try {
//            TblModelAlternatives tblModel = (TblModelAlternatives) ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getModel();
//            int columnIndex = ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedColumn();
//            int rowIndex = ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedRow();
//            System.out.println("selected column index: "+columnIndex+" selected row index: "+rowIndex );
//            ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter).insertMark(ACStorage.getInstance().getGoal().getListAlternative().get(rowIndex), ACStorage.getInstance().getGoal().getListAlternative().get(columnIndex - 1), Math.abs(jSlider1.getValue()) + 1);
////            treba li da se uzpe allAlternativeRanks preko Criteria umesto listAlternative??
//            tblModel.fireTableDataChanged();
//        } catch (MarkNotInSatScaleException ex) {
//            Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }//GEN-LAST:event_slderMarkAlternativesStateChanged
    
    private void slderMarkAlternativesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_slderMarkAlternativesKeyReleased
    }//GEN-LAST:event_slderMarkAlternativesKeyReleased
    
    private void slderMarkAlternativesMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_slderMarkAlternativesMouseReleased
        System.out.println(slderMarkAlternatives.getValue());
        if (((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedColumn() > -1
                && ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedRow() > -1) {
            try {
                TblModelAlternatives tblModel = (TblModelAlternatives) ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getModel();
                int columnIndex = ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedColumn();
                int rowIndex = ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().getSelectedRow();
                System.out.println("selected column index: " + columnIndex + " selected row index: " + rowIndex);
                if (slderMarkAlternatives.getValue() >= 0) {
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter).insertMark(
                            ACStorage.getInstance().getGoal().getListAlternative().get(columnIndex - 1),
                            ACStorage.getInstance().getGoal().getListAlternative().get(rowIndex),
                            Math.abs(slderMarkAlternatives.getValue()) + 1);
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter).insertMark(
                            ACStorage.getInstance().getGoal().getListAlternative().get(rowIndex),
                            ACStorage.getInstance().getGoal().getListAlternative().get(columnIndex - 1),
                            1.0 / (Math.abs(slderMarkAlternatives.getValue()) + 1));
//            treba li da se uzpe allAlternativeRanks preko Criteria umesto listAlternative??
                    tblModel.fireTableDataChanged();
                } else {
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter).insertMark(
                            ACStorage.getInstance().getGoal().getListAlternative().get(columnIndex - 1),
                            ACStorage.getInstance().getGoal().getListAlternative().get(rowIndex),
                            1.0 / (Math.abs(slderMarkAlternatives.getValue()) + 1));
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter).insertMark(
                            ACStorage.getInstance().getGoal().getListAlternative().get(rowIndex),
                            ACStorage.getInstance().getGoal().getListAlternative().get(columnIndex - 1),
                            Math.abs(slderMarkAlternatives.getValue()) + 1);
                    tblModel.fireTableDataChanged();
                }
            } catch (MarkNotInSatScaleException ex) {
                Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(Level.SEVERE, null, ex);
                
            }
        }
        slderMarkAlternatives.setValue(0);
    }//GEN-LAST:event_slderMarkAlternativesMouseReleased
    
    private void btnPreviousActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPreviousActionPerformed
        --criteriaCounter;
        if (ACStorage.getInstance().getGoal().getListCriteria().size() > criteriaCounter) {
            TblModelAlternatives tblModelAlternatives = new TblModelAlternatives(
                    ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter));
            ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().setModel(tblModelAlternatives);
        }
        checkButtons();
    }//GEN-LAST:event_btnPreviousActionPerformed
    
    private void btnAverageValuesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAverageValuesActionPerformed
        TblModelAverageValues tbAver  = new TblModelAverageValues(ACStorage.getInstance().getGoal().getListCriteria().get(criteriaCounter));
        ((PnlAlternativeMarks) pnlTable).getTblAlternativeMarks().setModel(tbAver);
    }//GEN-LAST:event_btnAverageValuesActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmRankAlternativesByCriteria.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                FrmRankAlternativesByCriteria dialog = new FrmRankAlternativesByCriteria(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAverageValues;
    private javax.swing.JButton btnNext;
    private javax.swing.JButton btnNormalize;
    private javax.swing.JButton btnPrevious;
    private javax.swing.JComboBox cmbNormalize;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel pnlOptions;
    private javax.swing.JPanel pnlSlider;
    private javax.swing.JPanel pnlTable;
    private javax.swing.JSlider slderMarkAlternatives;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the panelAC
     */
    public JPanel getPanelAC() {
        return panelAC;
    }

    /**
     * @param panelAC the panelAC to set
     */
    public void setPanelAC(JPanel panelAC) {
        this.panelAC = panelAC;
        repaint();
        pack();
    }
    
    public void setActivePanel(JPanel noviPanel) {
        if (pnlTable != null) {
            this.remove(pnlTable);
        }
        
        pnlTable = noviPanel;
        getContentPane().add(pnlTable, java.awt.BorderLayout.CENTER);
        pnlTable.setVisible(true);
        validate();
        repaint();
        pack();
    }
    
    private void checkButtons() {
        if (criteriaCounter == ACStorage.getInstance().getGoal().getListCriteria().size() - 1) {
            btnNext.setEnabled(false);
        } else {
            btnNext.setEnabled(true);
        }
        if (criteriaCounter == 0) {
            btnPrevious.setEnabled(false);
        } else {
            btnPrevious.setEnabled(true);
        }
    }
}
